/*******************************************************************************
 *	                           bsp ram clear.c
 *******************************************************************************/
#include "bsp.h"
#include "common.h"
#include "stdint.h"

/*******************************************************************************
 * @brief  stack infomation
 *******************************************************************************/
#define VECT_ADDR 0x8000000
#define STACK_SIZE 0x400

/*******************************************************************************
 * @brief  mem_clr define
 * \param[in] none
 * \retval: none
 *******************************************************************************/
#define mem_clr(base, size, val) \
	pdata = (uint32_t *)(base);  \
	Len = (size) / 4;            \
	while (Len--)                \
	{                            \
		*pdata++ = val;          \
	}

/*******************************************************************************
 * @brief  stack init, keil 进入mian时，SP=Vect[0]
 * \param[in] none
 * \retval: none
 *******************************************************************************/
void stack_init(void)
{
	volatile uint32_t *pdata;
	register uint32_t Len;
	register uint32_t addr;

	// stack
	addr = inpw(VECT_ADDR) - STACK_SIZE;
	mem_clr(addr, STACK_SIZE - 0x20, 0xEFEFEFEF);
}

/*******************************************************************************
 * @brief  stack_used
 * \param[in] none
 * \retval:  千分数
 *******************************************************************************/
uint16_t stack_used(void)
{
	uint32_t unused = 0;
	uint32_t *pdata;
	register uint32_t ofsset;
	register uint32_t addr;

	addr = inpw(VECT_ADDR) - STACK_SIZE;
	pdata = (uint32_t *)addr;

	for (ofsset = 0; ofsset < STACK_SIZE; ofsset += 4)
	{
		if (0xEFEFEFEF == *pdata++)
		{
			unused += 4;
		}
		else
		{
			break;
		}
	}

	return (1000 - unused * 1000 / STACK_SIZE);
}
